#include "Directx.h"
#include "WinGlobal.h"
#include "Definitions.h"

int g_currentScreenWidth;
int g_currentScreenHeight;

DirectXFramework::DirectXFramework()
{
	g_currentScreenWidth = 800;
	g_currentScreenHeight = 450;
	fullscreen = false;

	//direct3d
	pD3D = Direct3DCreate9(D3D_SDK_VERSION);

	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
	d3dpp.BackBufferCount  = 1;
	d3dpp.BackBufferHeight = SCREEN_HEIGHT;
	d3dpp.BackBufferWidth  = SCREEN_WIDTH;
	d3dpp.hDeviceWindow    = g_wndHandle;
	
	SetWindowLong(d3dpp.hDeviceWindow, GWL_STYLE, WS_OVERLAPPEDWINDOW);
	SetWindowPos(d3dpp.hDeviceWindow, HWND_TOP, 0, 0, 640, 480, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
	
	pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_wndHandle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pd3dDevice);
    
	pd3dDevice->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(255, 255, 255));
	pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
	pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);

	//sprite
	D3DXCreateSprite(pd3dDevice, &sprite);
	spriteList.Init(pd3dDevice);
}

void DirectXFramework::ToggleFullScreen()
{
	//current		wanted
	fullscreen = !fullscreen;
	if(fullscreen)
	{
		g_currentScreenWidth = GetSystemMetrics(SM_CXSCREEN);
		g_currentScreenHeight = GetSystemMetrics(SM_CYSCREEN);
		SetWindowLong(d3dpp.hDeviceWindow, GWL_STYLE, WS_POPUPWINDOW);
	}
	else
	{
		g_currentScreenWidth = SCREEN_WIDTH;
		g_currentScreenHeight = SCREEN_HEIGHT;
		SetWindowLong(d3dpp.hDeviceWindow, GWL_STYLE, WS_OVERLAPPEDWINDOW);
	}
	SetWindowPos(d3dpp.hDeviceWindow, HWND_TOP, 0, 0, g_currentScreenWidth, g_currentScreenHeight, SWP_FRAMECHANGED | SWP_DRAWFRAME | SWP_SHOWWINDOW);
}

void DirectXFramework::Render(LostVector<DrawStruct>* DrawList)
{
	// Clear the backbuffer to a black color
	pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0 );

	pd3dDevice->BeginScene();
	
	sprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_DEPTH_FRONTTOBACK);

	for(int i=0;i<DrawList->Size();++i)
		spriteList.draw(sprite, DrawList->get(i));

	sprite->End();

	pd3dDevice->EndScene();

	// Present the backbuffer contents to the display
	pd3dDevice->Present( NULL, NULL, NULL, NULL );
}

DirectXFramework::~DirectXFramework()
{
	sprite->Release();
	pd3dDevice->Release();
	pD3D->Release();
}